package
{
	import flash.display.BitmapData;
	import flash.events.Event;
	import flash.display.*;
	import flash.utils.*;
	import flash.net.URLRequest;
	import org.flixel.*;
	import org.flixel.system.FlxTile;
	import MagneticFields;

	public class PlayState extends FlxState
	{
		[Embed(source="../assets/jump.mp3")] private var som_pulo:Class;
		[Embed(source="../assets/coin.mp3")] private var som_coin:Class;
		[Embed(source="../assets/win.mp3")] private var som_win:Class;

		
		
		// ----------------------------------------- 
		//			BMP DOS LEVELS
		// ----------------------------------------- 
		[Embed(source = "../assets/level_0.png")]  static public var bitmap_level_1:Class;
		[Embed(source = "../assets/level_1.png")]  static public var bitmap_level_2:Class;
		[Embed(source = "../assets/level_2.png")]  static public var bitmap_level_3:Class;
		[Embed(source = "../assets/level_3.png")]  static public var bitmap_level_4:Class;
		[Embed(source = "../assets/level_4.png")]  static public var bitmap_level_5:Class;
		[Embed(source = "../assets/level_5.png")]  static public var bitmap_level_6:Class;
		
		[Embed(source = "../assets/bateria.PNG")]  static public var bateria:Class;
		[Embed(source = "../assets/bg1.png")]  static public var BackgroundImageClass:Class;
		private var background:FlxSprite;

		private var n_levels:int;	
			
		public var level:FlxTilemap;
		public var exit:FlxSprite;
		public var coins:FlxGroup;
		public var player:Spherobot;
		public var score:FlxText;
		public var status:FlxText;
		
		
		public var magnetics:FlxGroup;
		public var magneticFields:FlxGroup;
		
		// --cabelo parts
		public var imaLabel:FlxText;
        public var molaLabel:FlxText;
        public var dardoLabel:FlxText;
		
		public var flixelButton:Array;
        
        public var ima:Boolean;
        public var imaNumber:int;
        
        public var mola:Boolean;
        public var molaNumber:int;
        
        public var dardo:Boolean;
        public var dardoNumber:int;
		// --
		
		
	public var gameName:FlxText;
	
	public function showGameName():void
	{
		gameName = new FlxText(FlxG.width/2, 2, FlxG.height);
		gameName.shadow = 0xff000000;
		gameName.alignment = "center";
		gameName.text = "Labirinto";
		add(gameName);
	}

		override public function create():void
		{
			// ----------------------------------------- 
			//			IMPORTANTE - QUANTIDADE DE LEVELS
			// ----------------------------------------- 
			n_levels = 6;
			
			
			// imagem de fundo
			background = new FlxSprite(0, 0, BackgroundImageClass);
			add(background);		
			showGameName();
			// Mouse: http://www.zoklet.net/bbs/showthread.php?t=140683
			FlxG.mouse.show();
			
			
			// create a bitmap of the embedded
			var pic:Bitmap;
			switch(FlxG.score) {
				case 0: pic = new bitmap_level_1(); break;
				case 1: pic = new bitmap_level_2(); break;
				case 2: pic = new bitmap_level_3(); break;
				case 3: pic = new bitmap_level_4(); break;
				case 4: pic = new bitmap_level_5(); break;
				case 5: pic = new bitmap_level_6(); break;

			}
	
			//Create a new tilemap using our level data
			level = new FlxTilemap();
			var data:BitmapData = pic.bitmapData;
			level.loadMap(FlxTilemap.bitmapToCSV(data), FlxTilemap.ImgAuto, 0, 0, FlxTilemap.AUTO);
			add(level);
			
			
			
		

			//Create coins to collect (see createCoin() function below for more info)
			coins = new FlxGroup();
			magnetics = new FlxGroup();
			magneticFields = new FlxGroup();
			//Top left coins
			
			// -----------------------------
			// ADICIONAR MOEDAS, ENTRADA E SAIDA
			// -----------------------------
			var pontoEntrada:FlxPoint = new FlxPoint(0, 0);
			var pontoSaida:FlxPoint = new FlxPoint(0, 0);
			for (var i:int = 0; i < data.width; i++)
			for (var j:int = 0; j < data.height;j++) {
				var pixel:uint = data.getPixel(i, j);
				
				//trace(pixel.toString(16));
				if (pixel.toString(16) == "ff0000") createCoin(i, j); 	// RED = moedas
				
				else if (pixel.toString(16) == "f0f0f0") { 				// = entrada
					pontoEntrada.x = i;
					pontoEntrada.y = j;
				}
				else if (pixel.toString(16) == "333333")				// = saída
				{
					pontoSaida.x = i;
					pontoSaida.y = j;
					
				}
			}
			trace("saida = "+pontoSaida.x + ", "+ pontoSaida.y);
			
			
			
			// saída (bateria)
			exit = new FlxSprite(pontoSaida.x*8,pontoSaida.y*8,bateria);
			exit.exists = true;
			add(exit);
	
			add(magnetics);
			add(magneticFields);
			add(coins);
			//Create player (a red box)
			
			//(x:Number = 0, y:Number = 0, width:uint = 10, height:uint = 10, simpleGraphic:Class = null, color:uint=0xffffffff)
			player = new Spherobot (pontoEntrada.x*8, pontoEntrada.y*8, 10, 10, null, 0xffaa1111);
		
				add(player);

			score = new FlxText(2,2,80);
			score.shadow = 0xff000000;
			score.text = "SCORE: "+(coins.countDead()*100);
			add(score);
			
			status = new FlxText(200,2,160);
			status.shadow = 0xff000000;
			status.alignment = "right";
			
			// ----------------------------------------- 
			//			CONTAGEM DE LEVEL
			// ----------------------------------------- 
			status.text = "(level "+(FlxG.score+1)+") Recupere a bateria!";
			
			add(status);
			
			// --cabelo parts
			
			var x_base_menu:int = FlxG.width/6;
			var x_offset_menu:int = 40;
			var y_base_menu:int = 340;
			var y_offset_menu:int = -4;
			
			var flixelButton:FlxButton = new FlxButton( 1, x_base_menu, y_base_menu, "i", onFlixel);
            imaNumber = 100;
            add(flixelButton);
            
            imaLabel = new FlxText(x_base_menu,y_base_menu+40,80);
            imaLabel.shadow = 0xff000000;
            imaLabel.text = "X "+imaNumber.toString();
            add(imaLabel);
            
            
            var flixelButton1:FlxButton = new FlxButton( 2, x_base_menu+x_offset_menu, y_base_menu, "m", onFlixel1);
            molaNumber = 100;
            add(flixelButton1);
            
            molaLabel = new FlxText(x_base_menu+x_offset_menu,y_base_menu+40,80);
            molaLabel.shadow = 0xff000000;
            molaLabel.text = "X "+molaNumber.toString();
            add(molaLabel);
            
            var flixelButton2:FlxButton = new FlxButton( 3, x_base_menu+x_offset_menu*2, y_base_menu, "d", onFlixel2);
            dardoNumber = 2;
            add(flixelButton2);
            
            dardoLabel = new FlxText(x_base_menu+x_offset_menu*2,y_base_menu+40,80);
            dardoLabel.shadow = 0xff000000;
            dardoLabel.text = "X "+dardoNumber.toString();
            add(dardoLabel);
            
            /*var flixelButton1:FlxButton = new FlxButton(FlxG.width / 2 - 40, FlxG.height / 3 + 54, "uio", onFlixel);
            
            flixelButton.color = 0xff729954;
            flixelButton.label.color = 0xffd8eba2;
            add(flixelButton);*/
        }
        
        public function onFlixel():void
        {
            ima = true;
            mola = false;
            dardo = false;
        }
        
        public function onFlixel1():void
        {
            mola = true;
            ima = false;
            dardo = false;
        }
        
        public function onFlixel2():void
        {
            dardo = true;
            ima = false;
            mola = false;
        }
			
		// --
			
			
		

		//creates a new coin located on the specified tile
		public function createCoin(X:uint,Y:uint):void
		{
			var coin:FlxSprite = new FlxSprite(X*8+3,Y*8+2);
			coin.makeGraphic(2,4,0xffffff00);
			coins.add(coin);
		}
		
		public function createMagnetic(x:uint, y:uint, raio:uint, magneticPolo:Boolean):void
		{
			//var magnet:Magnet = new Magnet(x*8 + 3, y*8 + 2, raio, magneticPolo);
			var magnet:Magnet = new Magnet(x, y, raio, magneticPolo);
			
			magnetics.add(magnet);
			magneticFields.add(magnet.field);
		}

		override public function update():void
		{
				
			if ( player.isTouching(FlxObject.FLOOR) ) player.hasHitFloor();
			if ( player.isTouching(FlxObject.WALL) ) player.hasHitWall();
			player.zeroForces();
			// -----------------
		/*	var t = new FlxText(2,25,200);
			t.shadow = 0xff000000;
			t.text = "resultForce.x: "+(player.resultForce.x);
			add(t);
			
			var t1 = new FlxText(2,35,200);
			t1.shadow = 0xff000000;
			t1.text = "externalForces.x: "+(player.externalForces.x);
			add(t1);
			
			var t1 = new FlxText(2,45,200);
			t1.shadow = 0xff000000;
			t1.text = "acceleration.x: "+(player.acceleration.x);
			add(t1);*/
			
			
			// -----------------
			
			// -- cabelo parts
			 if (FlxG.mouse.justPressed() /*&& FlxG.mouse.x < player.x + 11 && FlxG.mouse.x > player.x - 11 && FlxG.mouse.y > player.y -11 && FlxG.mouse.y < player.y +11*/ ) 
			 {
                

				 
				 
                if (ima && imaNumber > 0) {
                    
                    ima = false;
                    
                    //TODO
					createMagnetic(FlxG.mouse.x, FlxG.mouse.y, 45, true);
					
                    imaNumber = imaNumber - 1;
                    imaLabel.text = "X "+imaNumber.toString();
                }
                
                else if (mola && molaNumber > 0) {

                    mola = false;
                    
                    //TODO
                    createMagnetic(FlxG.mouse.x, FlxG.mouse.y, 45, false);
					
                    molaNumber = molaNumber - 1;
                    molaLabel.text = "X "+molaNumber.toString();
                    
                }
                
                else if (dardo && dardoNumber > 0) {

                    dardo = false;
                    
                    //TODO
                    
                    dardoNumber = dardoNumber - 1;
                    dardoLabel.text = "X "+dardoNumber.toString();
                    
                }
				
				
				
					add(magnetics);
					add(magneticFields);
				
                
            }
			
			// --
			
			
			//Player movement and controls
			//player.acceleration.x = 0;
			//if(FlxG.keys.LEFT)
			//	player.acceleration.x = -player.maxVelocity.x*4;
			//if(FlxG.keys.RIGHT)
			//	player.acceleration.x = player.maxVelocity.x*4;
			if (FlxG.keys.justPressed("SPACE") && player.isTouching(FlxObject.ANY)) {
				FlxG.play(som_pulo);
				player.velocity.y = -player.maxVelocity.y/2;
			}
				
			FlxG.overlap(magneticFields, player, calculateMagneticForce);	
	
			//Updates all the objects appropriately
			super.update();
	
				
			//Check if player collected a coin or coins this frame
			FlxG.overlap(coins,player,getCoin);

			//Check to see if the player touched the exit door this frame
			FlxG.overlap(exit, player, win);
			
			
			
			//Finally, bump the player up against the level
			FlxG.collide(level, player);
		
			

			//Check for player lose conditions
			if(player.y > FlxG.height)
			{
				FlxG.score = 0; //sets status.text to "Aww, you died!"
				FlxG.resetState();
			}
		}
		
		public function calculateMagneticForce(magneticFields:MagneticFields, player:Spherobot)
		{
			var d:FlxPoint;
			var d2:Number;
			var force:FlxPoint;
			
			d = new FlxPoint();
			force = new FlxPoint();
						
			if (magneticFields.polo == true)
			{
				force.x = 10;
				force.y = 0;
			}
			else if (magneticFields.polo == false)
			{
				force.x = -10;
				force.y = 0;
			}
			
			player.addExternalForce(force);
		}
		
		//Called whenever the player touches a coin
		public function getCoin(Coin:FlxSprite,Player:FlxSprite):void
		{
			FlxG.play(som_coin);
			Coin.kill();
			score.text = "SCORE: "+(coins.countDead()*100);
			if(coins.countLiving() == 0)
			{
				//status.text = "Find the exit.";
				//exit.exists = true;
			}
		}

		// ----------------------------------------- 
		//			AVANÇO DE LEVEL (GANHOU)
		// -----------------------------------------
		public function win(Exit:FlxSprite,Player:FlxSprite):void
		{
			status.text = "Parabéns!";
			FlxG.play(som_win);
			
			 var init:int = getTimer();
    while(true) {
        if(getTimer() - init >= 300) {
            break;
        }
    }
			
			FlxG.score = (FlxG.score + 1) % n_levels;
			Player.kill(); 
			FlxG.resetState();
		}
	}
}